/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.web.utils;

import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 类作用：Web端工具类
 * 
 * @author Johnny@cn.ibm.com
 */
public class WebUtils {
	private static Logger log = LoggerFactory.getLogger(WebUtils.class);

	/**
	 * 取得指定的Session变量值
	 * 
	 * @param attr
	 *            变量名
	 * @return Session中变量值
	 */
	public static Object getSessionAttribute(String attr) {
		return RequestContextHolder.getRequestAttributes().getAttribute(attr, RequestAttributes.SCOPE_SESSION);
	}
	
	/**
	 * 把请求参数组装到指定的对象属性中
	 * 
	 * @param <T>   要组装的对象类型
	 * @param clazz 要组装的对象类
	 * @param req   请求
	 * @return 组装好的对象
	 */
	public static <T> T getRequestObject(Class<T> clazz, HttpServletRequest req) {
		// Enumeration<String> names = req.getParameterNames();
		T data = BeanUtils.instantiateClass(clazz);
		ServletRequestDataBinder dbind = new ServletRequestDataBinder(data);
		dbind.bind(req);
		// while (names.hasMoreElements()) {
		// String name = names.nextElement();
		// if (name.indexOf(".") > 0) {
		//
		// } else {
		// setPropertyValue(data, name, req);
		// }
		// }
		return data;
	}

	public static String getUserLanguage() {
		Locale loc = LocaleContextHolder.getLocale();
		String lang = loc.getLanguage() + "_" + loc.getCountry();
		return lang;
	}
	static <T> void setPropertyValue(T targetObject, String propName, HttpServletRequest req) {
		PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(targetObject.getClass(), propName);
		if (pd == null) {
			return;
		}
		Class<?> pt = pd.getPropertyType();
		try {
			Object v = null;
			if (pt.isArray()) {
				v = req.getParameterValues(propName);
			} else {
				String vs = req.getParameter(propName);
				if (pt.isEnum()) {

					for (Object o : pt.getEnumConstants()) {
						if (((Enum<?>) o).name().equals(vs)) {
							v = o;
							break;
						}
					}
				} else if (String.class.isAssignableFrom(pt)) {
					v = vs;
				} else if (Date.class.isAssignableFrom(pt)) {
					if (vs.contains("-")) {
						String dp = vs.contains("-") ? "yyyy-MM-dd" : "yyyyMMdd";
						if (vs.contains(":")) {
							dp += " HH:mm:ss";
						}
						v = DateUtils.parseDate(vs, dp);
					}
					try {
						v = new Date(Long.valueOf(vs));
					} catch (NumberFormatException e) {
						log.error("unknown date format:{}", vs);
					}
				} else if (Integer.class.equals(pt) || int.class.equals(pt)) {
					v = Integer.valueOf(vs);
				} else if (Long.class.equals(pt) || long.class.equals(pt)) {
					v = Long.valueOf(vs);
				} else if (Double.class.equals(pt) || double.class.equals(pt)) {
					v = Double.valueOf(vs);
				} else if (Boolean.class.equals(pt) || boolean.class.equals(pt)) {
					v = Boolean.valueOf(vs);
				} else if (Float.class.equals(pt) || float.class.equals(pt)) {
					v = Float.valueOf(vs);
				} else {
					log.error("unknown type of parameter {} value:{}", propName, vs);
				}
			}
			pd.getWriteMethod().invoke(targetObject, v);
		} catch (Exception e) {
			log.error("Can't convert parameters to {}", targetObject.getClass());
		}

	}
}
